package com.supermarket.manage.business.usermanage.controller;

import com.supermarket.manage.common.constant.ExportConstant;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.PageBean;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.ucenter.request.AddUserParams;
import com.supermarket.manage.common.dto.ucenter.request.UserAddRoleParams;
import com.supermarket.manage.common.dto.ucenter.request.UserPageParams;
import com.supermarket.manage.common.pojo.MyUser;
import com.supermarket.manage.common.utils.POIUtil;
import com.supermarket.manage.common.utils.TimeUtil;
import com.supermarket.manage.common.validation.CheckGroup;
import com.supermarket.manage.provider.api.ucenter.BuyerService;
import com.supermarket.manage.provider.api.ucenter.RoleManageService;
import com.supermarket.manage.provider.api.ucenter.UserManageService;
import com.supermarket.manage.provider.api.ucenter.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-02-28 17:46
 **/
@RestController
@RequestMapping("/userManage")
@Api(value = "UserManageController", tags = "用户管理接口")
public class UserManageController {
    @Reference(version = "1.0.0")
    private UserService userService;

    @Reference(version = "1.0.0")
    private BuyerService buyerService;

    @Reference(version = "1.0.0")
    private UserManageService userManageService;

    @Reference(version = "1.0.0")
    private RoleManageService roleManageService;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @PreAuthorize("hasAnyAuthority('/','/user/get')")
    @PostMapping("/userPageList")
    @ApiOperation(value = "用户列表", notes = "用户列表")
    public ResponseResult<PageBean<MyUser>> getUserPageList(@Validated({CheckGroup.Page.class})
                                                            @RequestBody UserPageParams params) {
        if (params.getBeginTime() != null) {
            if (params.getEndTime() == null) {
                return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "参数不完整:未获取到结束时间戳");
            }
            if (params.getBeginTime().compareTo(params.getEndTime()) > 0) {
                return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "参数非法：开始时间戳应小于结束时间戳");
            }
        }
        PageBean<MyUser> pageBean = userManageService.getUserPageList(params);
        if (pageBean == null) {
            return new ResponseResult<>(CodeStatus.FAIL, "查询失败，服务器异常");
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", pageBean);
    }

    @PreAuthorize("hasAnyAuthority('/','/user/get')")
    @GetMapping("/export")
    @ApiOperation(value = "用户列表导出", notes = "用户列表导出")
    public void export(@Validated({CheckGroup.Get.class}) UserPageParams params, HttpServletResponse response) throws IOException {
        List<MyUser> users = userManageService.getUserList(params);
        List<Map<String, Object>> maps = new ArrayList<>();
        users.forEach(d -> {
            Map<String, Object> map = new HashMap<>(4);
            map.put("username", d.getUsername());
            map.put("phone", d.getPhone());
            map.put("roleName", d.getRoleName());
            map.put("created", TimeUtil.formatDate(d.getCreated(), TimeUtil.TIME_FORMAT));
            maps.add(map);
        });
        String fileName = ExportConstant.USER_SHEETNAME + TimeUtil.getNow("yyyyMMdd");
        SXSSFWorkbook export = POIUtil.export(fileName, maps, ExportConstant.USER_HEADERSNAME, ExportConstant.USER_KEYS);

        POIUtil.writeTo(fileName, export, response);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/userInfo/{userId}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户id获取用户信息")
    public ResponseResult<MyUser> getUserInfoByUserId(@NotBlank(message = "userId不能为空")
                                                      @PathVariable("userId") String userId) {
        MyUser myUser = userService.getUserByUserId(Long.valueOf(userId));
        if (null == myUser) {
            return new ResponseResult<>(CodeStatus.FAIL, "查询失败，无此用户");
        }
        myUser.setPassword(null);
        return new ResponseResult<>(CodeStatus.OK, "请求成功", myUser);
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @GetMapping("/deleteUserById/{userId}/{buyerId}")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    public ResponseResult<Void> deleteUserById(@NotNull(message = "userId不能为空")
                                               @PathVariable("userId") Long userId,
                                               @NotBlank(message = "buyerId不能为空")
                                               @PathVariable("buyerId") String buyerId) {
        Boolean aBoolean = userManageService.deleteUserById(userId, buyerId);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "删除成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "删除失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @PostMapping("/addUser")
    @ApiOperation(value = "添加用户", notes = "添加用户")
    public ResponseResult<Void> addUser(@Validated @RequestBody AddUserParams params) {
        if (userService.getCountByUsername(params.getUsername()) > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "该用户名已被使用");
        }
        params.setPassword(passwordEncoder.encode(params.getPassword()));
        Boolean aBoolean = userManageService.addUser(params);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "添加成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "添加失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/user/manage')")
    @PostMapping("/assignRoleToUser")
    @ApiOperation(value = "修改用户角色", notes = "修改用户角色")
    public ResponseResult<Void> assignRoleToUser(@Validated @RequestBody UserAddRoleParams userAddRoleParams) {
        Boolean aBoolean = userManageService.assignRoleToUser(userAddRoleParams);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "分配成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "分配失败");
    }

}
